package com.dbq.fast.business.product.api;


import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.dbq.fast.App;
import com.dbq.fast.BuildConfig;
import com.dbq.fast.business.login.api.LoginApi;
import com.dbq.fast.business.product.ProductTypeActivity;
import com.dbq.fast.business.product.bean.DoUserDiscount;
import com.dbq.fast.business.product.bean.GoogleReturnOrder;
import com.dbq.fast.business.product.bean.ProductType;
import com.dbq.fast.business.product.bean.ServiceType;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.HttpResult;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.common.net.RemoteApiSuccess;
import com.dbq.fast.util.SystemUtil;

import java.util.HashMap;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 */

public class ProductApi {

    public static void questService(RemoteApiCallBack callback) {
        User user = User.getInstance();
        HttpManager.getInstance().getHttpService()//
                .getVipService(SystemUtil.getLanguageCustom(App.getContext()), user.getToken(), user.getAccount())//
                .compose(new CommonTransformer<>()).retry(3)
                .subscribe(httpResult -> {
                    int code = httpResult.getCode();
                    if (code == 200) {
                        ServiceType serviceType = httpResult.getData();
                        if (serviceType != null) {
                            List<ServiceType.AppServiceListBean> list = serviceType.appServiceList;
                            callback.onSuccess(list);
                        }
                    } else if (code == 401) {
                        LoginApi.refreshToken(true, new RemoteApiCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {
                                questService(callback);
                            }

                            @Override
                            public void onFail(int status, String message) {
                                callback.onFail(404, "");
                            }
                        });
                    } else if (code == 402) { //其他设备登录
                        callback.onFail(code, ""/*App.getContext().getString(R.string.login_on_other_device)*/);
                    } else {
                        callback.onFail(httpResult.getCode(), httpResult.getMsg());
                    }
                }, throwable -> {
                    Log.i("throwable", "throwable  = " + throwable.toString());
                    callback.onFail(404, "");
                });

    }

    /**
     * 请求套餐详细数据
     *
     * @param serviceId
     * @param serviceLevel
     * @param callbackProduct
     */
    public static void getProductList(long serviceId, int serviceLevel, RemoteApiCallBack callbackProduct) {
        User user = User.getInstance();
        HashMap hashMap = new HashMap();
        hashMap.put("account", user.getAccount());
        hashMap.put("serviceId", serviceId);
        hashMap.put("serviceLevel", serviceLevel); //当前服务等级
        hashMap.put("payPlatform", 0); //购买平台 0:安卓 1：IOS
        HttpManager.getInstance().getHttpService()//
                .getProduct(user.getToken(), hashMap)//
                .compose(new CommonTransformer<HttpResult<ProductType>>())//
                .subscribe((Consumer<HttpResult<ProductType>>) httpResult -> {
                    int code = httpResult.getCode();
                    if (httpResult.isSuccess() || code == 425) {
                        ProductType serviceType = httpResult.getData();

                        if (serviceType != null) {
                            for (ProductType.SetMealListBean i : serviceType.setMealList) {
                                i.isInvalid = httpResult.getCode() == 425;
                            }
                            callbackProduct.onSuccess(serviceType);
                        }
                    } else if (code == 401) {
                        LoginApi.refreshToken(true, new RemoteApiCallBack<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {
                                getProductList(serviceId, serviceLevel, callbackProduct);
                            }

                            @Override
                            public void onFail(int status, String message) {
                                callbackProduct.onFail(404, "");
                            }
                        });
                    } else if (code == 402) { //其他设备登录
                        callbackProduct.onFail(code, ""/*App.getContext().getString(R.string.login_on_other_device)*/);
                    } else {
                        callbackProduct.onFail(httpResult.getCode(), httpResult.getMsg());
                    }
                }, throwable -> {
                    Log.i("throwable", "throwable = " + throwable.toString());
                    callbackProduct.onFail(233, "");
                });
    }


    public static void afterCoupons(int userDisId, int disId, long setMealId, RemoteApiCallBack c) {
        HashMap hashMap = new HashMap();
        hashMap.put("userDisId", userDisId);
        hashMap.put("disId", disId);
        hashMap.put("setMealId", setMealId);
        HttpManager.getInstance().getHttpService()//
                .getAfterCoupons(User.getInstance().getToken(), hashMap)//
                .compose(new CommonTransformer<>())//
                .subscribe(new Consumer<HttpResult>() {
                    @Override
                    public void accept(HttpResult httpResult) throws Exception {
                        if (httpResult.getCode() == 200) {
                            c.onSuccess(httpResult.getData());
                        } else if (httpResult.getCode() == 401) {
                            LoginApi.refreshToken(true, new RemoteApiCallBack<Boolean>() {
                                @Override
                                public void onSuccess(Boolean aBoolean) {
                                    afterCoupons(userDisId, disId, setMealId, c);
                                }

                                @Override
                                public void onFail(int status, String message) {
                                    c.onFail(404, "");
                                }
                            });
                        }
                    }
                }, throwable -> {
                    c.onFail(404, "");
                });
    }

    public static void stripePay(Activity activity, ProductType.SetMealListBean checkProduct, String payToken, RemoteApiCallBack c) {
        User user = User.getInstance();
        HashMap hashMap = new HashMap();
        hashMap.put("account", user.getAccount());
        hashMap.put("payPlatform", "0"); //系统类型安卓：0;IOS:2
        hashMap.put("source", payToken);
        hashMap.put("setMealId", checkProduct.setMealId);
        hashMap.put("isRenew", checkProduct.isRenew);
        hashMap.put("country", SystemUtil.getCountry(activity.getBaseContext()));
        hashMap.put("versionName", BuildConfig.VERSION_NAME);
        HttpManager.getInstance().getHttpService()
                .stripPay(user.getToken(), hashMap)
                .compose(new CommonTransformer<>())
                .subscribe(httpResult -> {
                    if (httpResult.isSuccess()) {
                        c.onSuccess("");
                    } else {
                        c.onFail(httpResult.getCode(), httpResult.getMsg());
                    }
                }, throwable -> {
                    c.onFail(400, throwable.getMessage());
                });
    }

    public static void submitOrder(Activity activity, String dataSignature, String purchaseData,//
                                   ProductType.SetMealListBean checkProduct, RemoteApiSuccess<HttpResult<DoUserDiscount>> remoteApiSuccess) {
        GoogleReturnOrder gro = GsonT.parseJson(purchaseData, GoogleReturnOrder.class);
        HashMap data = new HashMap();
        data.put("account", User.getInstance().getAccount());
        data.put("dataSignature", dataSignature);
        data.put("productId", gro.productId);
        data.put("isRenew", checkProduct.isRenew);
        data.put("payPlatform", "0");
        data.put("country", SystemUtil.getCountry(activity));
        data.put("orderId", gro.orderId);
        data.put("purchaseState", gro.purchaseState);
        data.put("purchaseToken", gro.purchaseToken);
        data.put("packageName", activity.getPackageName());
        data.put("setMealId", checkProduct.setMealId);
        data.put("versionName", BuildConfig.VERSION_NAME);

        HttpManager.getInstance().getHttpService()//
                .submitOrder(User.getInstance().getToken(), data)//
                .compose(new CommonTransformer<>())//
                .subscribe(httpResult -> {
                    if (httpResult.isSuccess()) {
                        if (remoteApiSuccess != null) {
                            remoteApiSuccess.onSuccess(httpResult);
                        }
                    }
                }, throwable -> {
                    Log.i("throwable", throwable.toString());
                });
    }
}
